package com.gmlive.plugin.jenkins

import com.android.build.gradle.AppExtension
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File

class JenkinsPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        checkAppModule(project)

        project.extensions.create("jenkinsConfig", JenkinsExtension::class.java)

        project.afterEvaluate {
            val android = project.extensions.findByName("android") as AppExtension

            // 通过属性控制是否需要加固
            val useReinforce = project.properties.getOrDefault("useReinforce", "false").toString().equals("true", true)
            println("[Jenkins]==== 是否使用加固功能: $useReinforce ====")

            // 通过属性控制是否需要加固
            val useBundle = project.properties.getOrDefault("useBundle", "false").toString().equals("true", true)
            println("[Jenkins]==== 是否打aab包: $useBundle ====")

            android.applicationVariants.all { variant ->
                createJenkinsTask(project, variant.name.capitalize(), useReinforce, useBundle)
            }
        }

        if (File(project.rootDir, "config.hotfix").exists()) {
            println("[Jenkins]==== 发现config.hotfix文件，打补丁 ====")
            project.copy {
                it.from(File(project.rootDir, "config.hotfix").path)
                it.into("${project.projectDir}/robust")
            }
            project.apply(mapOf("plugin" to "auto-patch-plugin"))
        }
    }

    private fun checkAppModule(project: Project) {
        if (!project.plugins.hasPlugin("com.android.application")) {
            throw GradleException("Jenkins插件只能在主module中使用")
        }
    }

    private fun createJenkinsTask(project: Project, variantName: String, useReinforce: Boolean, useBundle: Boolean) {
        val taskName = "jenkins${variantName}"
        val hasReinforce = project.plugins.hasPlugin("appguard")
        val hasResguard = project.plugins.hasPlugin("AndResGuard")

        if (useReinforce && !hasReinforce) {
            throw GradleException("要开启加固功能，请先配置加固插件")
        }

        if (project.tasks.findByPath(taskName) == null) {
            val task = project.tasks.create(taskName, JenkinsTask::class.java)
            if (useBundle) {
                if (useReinforce) {
                    task.dependsOn("aabGuard$variantName")
                } else {
                    task.dependsOn("bundle${variantName}")
                }
            } else {
                when {
                    useReinforce -> {
                        task.dependsOn("apkGuard${variantName}")
                    }
                    hasResguard -> {
                        task.dependsOn("resguard${variantName}")
                    }
                    else -> {
                        task.dependsOn("assemble${variantName}")
                    }
                }
            }
        }
    }
}